//
//  AllPushViewController.m
//  HappinessTrip
//
//  Created by dllo on 15/10/9.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "AllPushViewController.h"
#import "UIImageView+WebCache.h"
#import "GetDataMethods.h"
#import "LabelTableViewCell.h"
#import "StoryTableViewCell.h"
#import "Recommendations.h"
#import "Comments.h"
#import "Detail_list.h"
#import "UserInformationViewController.h"
#import "Model.h"
#import "Fit.h"
#import "MBProgressHUD.h"

@interface AllPushViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *recommendationsArray;
@property(nonatomic, retain)NSMutableArray *commentsArray;
@property(nonatomic, retain)NSMutableArray *detail_listArray;
@property(nonatomic, retain)NSDictionary *tripDic;
@property(nonatomic, retain)NSDictionary *spotDic;

@property(nonatomic, retain)NSString *idString;
@property(nonatomic, retain)NSString *nameString;
@property(nonatomic, retain)NSString *userImage;
@property(nonatomic, retain)MBProgressHUD *progressView;

@end

@implementation AllPushViewController
-(void)dealloc
{
    [_tableView release];
    [_recommendationsArray release];
    [_commentsArray release];
    [_detail_listArray release];
    [_tripDic release];
    [_spotDic release];
    [super dealloc];
}

-(void)changeColor{
    self.tableView.backgroundColor = [Model shareInstance].BackgroundColor;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[Model shareInstance].TitleColor, NSForegroundColorAttributeName, nil]];
    self.navigationController.navigationBar.barTintColor = [Model shareInstance].BackgroundColor;
    [_tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"故事详情";
    [self changeColor];
}

-(void)getData
{
    self.recommendationsArray = [NSMutableArray array];
    self.commentsArray = [NSMutableArray array];
    self.detail_listArray = [NSMutableArray array];
    [GetDataMethods getDataByString:[NSString stringWithFormat:@"http://api.breadtrip.com/v2/new_trip/spot?spot_id=%@", _spot_id] BodyString:nil WithDataBlock:^(id data) {
        NSDictionary *dataDic = [data objectForKey:@"data"];
        //点击详情,游览记录
        self.spotDic = [NSDictionary dictionary];
        self.spotDic = [dataDic objectForKey:@"spot"];
        NSArray *recArray = [_spotDic objectForKey:@"recommendations"];
        for (NSDictionary *recDic in recArray) {
            Recommendations *rec = [[Recommendations alloc]init];
            [rec setValuesForKeysWithDictionary:recDic];
            [_recommendationsArray addObject:recDic];
        }
        NSArray *comArray = [_spotDic objectForKey:@"comments"];
        for (NSDictionary *comDic in comArray) {
            Comments *com = [[Comments alloc]init];
            [com setValuesForKeysWithDictionary:comDic];
            [_commentsArray addObject:com];
        }
        //信息列表(已使用)
        NSArray *detArray = [_spotDic objectForKey:@"detail_list"];
        for (NSDictionary *detDic in detArray) {
            Detail_list *det = [[Detail_list alloc]init];
            [det setValuesForKeysWithDictionary:detDic];
            [_detail_listArray addObject:det];
        }
        //用户头像点击数据
        _tripDic = [dataDic objectForKey:@"trip"];
        _idString = [[_tripDic objectForKey:@"user"] objectForKey:@"id"];
        _nameString = [[_tripDic objectForKey:@"user"] objectForKey:@"name"];
        _userImage = [[_tripDic objectForKey:@"user"] objectForKey:@"avatar_l"];
        [self createViews];
        [_tableView reloadData];
        [_progressView removeFromSuperview];
    }];
}
-(void)loadView
{
    [super loadView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor) name:@"changeColor" object:nil];
    [self getData];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor colorWithRed:1 green:0.95 blue:0.85 alpha:1];
    [self.view addSubview:_tableView];
    [_tableView release];
    
    //初始化加载中视图
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    _progressView.labelText = @"玩命加载中";
    [_progressView setMode:MBProgressHUDModeIndeterminate];
    [_progressView show:YES];
    _progressView.backgroundColor = [UIColor colorWithRed:0.73 green:0.76 blue:0.77 alpha:.3];
    [self.view addSubview:_progressView];
    [_progressView release];
    
}
-(void)createViews
{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 100 * H)];
    _tableView.tableHeaderView = headView;
    [headView release];
    UIImageView *userImageView = [[UIImageView alloc]initWithFrame:CGRectMake(20 * W, 20 * H, 50 * W, 50 * W)];
    userImageView.layer.cornerRadius = userImageView.frame.size.width / 2;
    userImageView.layer.masksToBounds = YES;
    [userImageView sd_setImageWithURL:[NSURL URLWithString:[[_tripDic objectForKey:@"user"] objectForKey:@"avatar_l"]]];
    UITapGestureRecognizer *userTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(userTapAction)];
    userImageView.userInteractionEnabled = YES;
    [userImageView addGestureRecognizer:userTap];
    [userTap release];

    [headView addSubview:userImageView];
    [userImageView release];
    UILabel *userLabel = [[UILabel alloc]initWithFrame:CGRectMake(userImageView.frame.origin.x + userImageView.frame.size.width + 10 * W, userImageView.frame.origin.y + 5 * H,  self.view.frame.size.width - userImageView.frame.size.width - 50 * W, 20 * H)];
    userLabel.text = [[_tripDic objectForKey:@"user"]objectForKey:@"name"];
    userLabel.textColor = [Model shareInstance].TitleColor;
    userLabel.font = [UIFont systemFontOfSize:15];
    [headView addSubview:userLabel];
    [userLabel release];
    UILabel *locationLabel = [[UILabel alloc]initWithFrame:CGRectMake(userLabel.frame.origin.x, userLabel.frame.origin.y + userLabel.frame.size.height, userLabel.frame.size.width, userLabel.frame.size.height)];
    //先判断是否为字典
    if ([[[self.spotDic objectForKey:@"poi"] class] isSubclassOfClass:[NSDictionary class]]) {
        //判断字典是否为空
        if ([[self.spotDic objectForKey:@"poi"]allKeys].count != 0) {
            locationLabel.text = [NSString stringWithFormat:@"故事发生在 %@", [[self.spotDic objectForKey:@"poi"] objectForKey:@"name"]];
            //关键字高亮
            //关键字标红效果
            NSString *keyWord = [[self.spotDic objectForKey:@"poi"] objectForKey:@"name"];
            NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:locationLabel.text];
            //获取关键字位置
            NSRange range = [locationLabel.text rangeOfString:keyWord];
            //设置关键字属性
            [attributeString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], NSForegroundColorAttributeName, [UIFont systemFontOfSize:18], NSFontAttributeName, nil] range:range];
            //添加到label
            locationLabel.attributedText = attributeString;
        }
        else {
            locationLabel.text =  [NSString stringWithFormat:@"故事发生在 %@", [self.spotDic objectForKey:@"location_alias"]];
            //关键字高亮
            //关键字标红效果
            NSString *keyWord = [self.spotDic objectForKey:@"location_alias"];
            NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc]initWithString:locationLabel.text];
            //获取关键字位置
            NSRange range = [locationLabel.text rangeOfString:keyWord];
            //设置关键字属性
            [attributeString setAttributes:[NSMutableDictionary dictionaryWithObjectsAndKeys:[UIColor lightGrayColor], NSForegroundColorAttributeName, [UIFont systemFontOfSize:18], NSFontAttributeName, nil] range:range];
            //添加到label
            locationLabel.attributedText = attributeString;
        }
    }
    else{
        locationLabel.text = @"";
    }
    
    locationLabel.font = [UIFont systemFontOfSize:15];
//    locationLabel.textColor = [Model shareInstance].TitleColor;
    [headView addSubview:locationLabel];
    [locationLabel release];
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(20 * W, 99 * H, 335 * W, 1 * H)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [headView addSubview:lineLabel];
    [lineLabel release];
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 375 * W, 100 * H)];
    _tableView.tableFooterView = footView;
    [footView release];
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        static NSString *identifier = @"cell";
        LabelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[LabelTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        if (self.spotDic != nil) {
            cell.introduceLabel.text = [self.spotDic objectForKey:@"text"];
        }
        cell.introduceLabel.textColor = [Model shareInstance].TitleColor;
        cell.backgroundColor = [Model shareInstance].BackgroundColor;
        return cell;
    }
    else {
        static NSString *identifier1 = @"cell1";
        StoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier1];
        if (!cell) {
            cell = [[StoryTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier1];
        }
        if (_detail_listArray.count != 0) {
            cell.detail = _detail_listArray[indexPath.row - 1];
            NSInteger width = [_detail_listArray[indexPath.row - 1] photo_width];
            NSInteger height = [_detail_listArray[indexPath.row - 1] photo_height];
            [cell setwidth:width height:height string:[_detail_listArray[indexPath.row - 1] text]];

        }
        cell.backgroundColor = [Model shareInstance].BackgroundColor;
        cell.contentLabel.textColor = [Model shareInstance].TitleColor;
        return cell;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return (_detail_listArray.count + 1);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if (_spotDic) {
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:20], NSFontAttributeName, nil];
            CGRect rect = [[_spotDic objectForKey:@"text"] boundingRectWithSize:CGSizeMake(335 * W, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
            return rect.size.height + 1;
        }
    }

    if (_detail_listArray .count != 0) {
        NSInteger width = [_detail_listArray[indexPath.row - 1] photo_width];
        NSInteger height = [_detail_listArray[indexPath.row - 1] photo_height];
        CGFloat bili = width / 335;
        CGFloat imageHeight = height / bili;
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15], NSFontAttributeName, nil];
        CGRect rect = [[_detail_listArray [indexPath.row - 1] text] boundingRectWithSize:CGSizeMake(335 * W, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return (rect.size.height + 1) + imageHeight + 40 * H;
    }
    return 0;
}

-(void)userTapAction
{
    UserInformationViewController *userVC = [[UserInformationViewController alloc]init];
    userVC.string = _idString;
    userVC.name = _nameString;
    userVC.user = _userImage;
    [self.navigationController pushViewController:userVC animated:YES];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
